import 'package:catsao/style/style.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class VideoThumbnail extends StatefulWidget {
  final String videourl;
  final double aspectRatiowidth;
  final double aspectRatioheight;

  const VideoThumbnail(
      {Key key,
      this.videourl,
      @required this.aspectRatiowidth,
      @required this.aspectRatioheight}
      )
      : super(key: key);

  @override
  _VideoThumbNail createState() => _VideoThumbNail();
}

class _VideoThumbNail extends State<VideoThumbnail> {
  VideoPlayerController videoPlayerController;

  @override
  void dispose() {
    //为了避免内存泄露，需要调用dispose
    videoPlayerController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    _onControllerChange(widget.videourl);
    super.initState();
  }

  void _initController(String link) {
    videoPlayerController = VideoPlayerController.network(widget.videourl)
      ..initialize().then((_) {
        setState(() {});
      });
  }

  Future<void> _onControllerChange(String link) async {
    if (videoPlayerController == null) {
      // If there was no controller, just create a new one
      _initController(link);
    } else {
      // If there was a controller, we need to dispose of the old one first
      final oldController = videoPlayerController;

      // Registering a callback for the end of next frame
      // to dispose of an old controller
      // (which won't be used anymore after calling setState)
      WidgetsBinding.instance.addPostFrameCallback((_) async {
        await oldController.dispose();

        // Initing new controller
        _initController(link);
      });

      // Making sure that controller is not used by setting it to null
      setState(() {
        videoPlayerController = null;
      });
    }
  }




  @override
  Widget build(BuildContext context) {
    return Center(
      child: Wrap(
        alignment: WrapAlignment.center,
        children: [
          SizedBox(
              height: 200,
              child: videoPlayerController.value.isInitialized
                  ? AspectRatio(
                      aspectRatio:
                          widget.aspectRatiowidth / widget.aspectRatioheight,
                      child: VideoPlayer(videoPlayerController),
                    )
                  : Container(
                      child: Center(
                      child: Text("加载中...",
                        style: StandardTextStyle.small.apply(
                        color: Colors.white,
                      ),),
                    )))
        ],
      ),
    );
  }
}
